package com.ruoyi.chat.service.impl;

import java.util.Date;
import java.util.List;

import com.ruoyi.chat.domain.Friendship;
import com.ruoyi.chat.domain.SysUser;
import com.ruoyi.chat.service.IFriendshipService;
import com.ruoyi.common.core.cond.AddFriendRequestCond;
import com.ruoyi.common.core.enums.VerifyStatusEnum;
import com.ruoyi.common.core.enums.YesNoEnum;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.vo.AddFriendUserVO;
import com.ruoyi.chat.service.ISysUserService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.chat.mapper.FriendRequestMapper;
import com.ruoyi.chat.domain.FriendRequest;
import com.ruoyi.chat.service.IFriendRequestService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 好友请求记录Service业务层处理
 * 
 * @author zhc
 * @date 2025-05-31
 */
@Service
public class FriendRequestServiceImpl implements IFriendRequestService 
{
    @Autowired
    private FriendRequestMapper friendRequestMapper;

    @Resource
    private ISysUserService iSysUserService;
    @Resource
    private IFriendshipService iFriendshipService;
    /**
     * 查询好友请求记录
     * 
     * @param id 好友请求记录主键
     * @return 好友请求记录
     */
    @Override
    public FriendRequest selectFriendRequestById(String id)
    {
        return friendRequestMapper.selectFriendRequestById(id);
    }

    /**
     * 查询好友请求记录列表
     * 
     * @param friendRequest 好友请求记录
     * @return 好友请求记录
     */
    @Override
    public List<FriendRequest> selectFriendRequestList(FriendRequest friendRequest)
    {
        return friendRequestMapper.selectFriendRequestList(friendRequest);
    }

    /**
     * 新增好友请求记录
     * 
     * @param friendRequest 好友请求记录
     * @return 结果
     */
    @Override
    public int insertFriendRequest(FriendRequest friendRequest)
    {
        return friendRequestMapper.insertFriendRequest(friendRequest);
    }

    /**
     * 修改好友请求记录
     * 
     * @param friendRequest 好友请求记录
     * @return 结果
     */
    @Override
    public int updateFriendRequest(FriendRequest friendRequest)
    {
        return friendRequestMapper.updateFriendRequest(friendRequest);
    }

    /**
     * 批量删除好友请求记录
     * 
     * @param ids 需要删除的好友请求记录主键
     * @return 结果
     */
    @Override
    public int deleteFriendRequestByIds(String[] ids)
    {
        return friendRequestMapper.deleteFriendRequestByIds(ids);
    }

    /**
     * 删除好友请求记录信息
     * 
     * @param id 好友请求记录主键
     * @return 结果
     */
    @Override
    public int deleteFriendRequestById(String id)
    {
        return friendRequestMapper.deleteFriendRequestById(id);
    }

    @Override
    public AddFriendUserVO addFriendQuery(String cond) {
        //todo 按钮显示
        LoginUser loginUser = SecurityUtils.getLoginUser();
        AddFriendUserVO userVO = iSysUserService.selectSysUserByPhoneOrUserName(cond);
        if(userVO==null){
            return null;
        }
        //找这个人有没有和我加过好友了
        userVO.setAddFriendButton(!iFriendshipService.isAlreadFriend(loginUser.getUserid(),userVO.getId()));
        return userVO;
    }

//    @Override
//    @Transactional
//    public Boolean addFriend(Long userId) {
//        LoginUser loginUser = SecurityUtils.getLoginUser();
//        return iFriendshipService.addFriend(initFriendShip(String.valueOf(loginUser.getUserid()),String.valueOf(userId)));
//    }

    @Override
    @Transactional
    public Boolean addFriendRequest(AddFriendRequestCond addFriendRequestCond) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if(loginUser.getUserid()==addFriendRequestCond.getUserId()){
            throw new ServiceException("不能添加自己为好友");
        }
        //判断有没有申请过
        if(friendRequestMapper.hasRequested(loginUser.getUserid(),addFriendRequestCond)){
            throw new ServiceException("不要重复申请");
        }
        addFriendRequestCond.setFriendRemark(StringUtils.hasText(addFriendRequestCond.getFriendRemark())? addFriendRequestCond.getFriendRemark() : addFriendRequestCond.getNickName());
        addFriendRequestCond.setRequestTime(new Date());
        return friendRequestMapper.addFriendRequest(loginUser.getUserid(),addFriendRequestCond);
    }

    @Override
    public List<AddFriendUserVO> queryFriendRequest() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        return friendRequestMapper.queryFriendRequest(loginUser.getUserid());
    }

    @Override
    @Transactional
    public Boolean executeFriend(Long id, String executeType) {
        FriendRequest friendRequest = friendRequestMapper.selectFriendRequestById(String.valueOf(id));
        if(friendRequest==null){
            throw new ServiceException("数据不存在");
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if(!String.valueOf(loginUser.getUserid()).equals(friendRequest.getFriendId())){
            throw new ServiceException("您无权限操作");
        }
        if(!VerifyStatusEnum.PENDING.getCode().equals(String.valueOf(friendRequest.getVerifyStatus()))){
            throw new ServiceException("请勿重复提交");
        }
        SysUser requestSender = iSysUserService.selectSysUserByUserId(Long.valueOf(friendRequest.getMyId()));
        SysUser currentUser = iSysUserService.selectSysUserByUserId(loginUser.getUserid());
        //修改状态
        friendRequest.setVerifyStatus(Long.valueOf(executeType));
        friendRequestMapper.updateFriendRequest(friendRequest);
        //如果同意，则加好友
        if(VerifyStatusEnum.PASS.getCode().equals(executeType)){
            iFriendshipService.addFriend(initFriendShip(friendRequest.getMyId(),friendRequest.getFriendId(),StringUtils.hasText(friendRequest.getFriendRemark())?friendRequest.getFriendRemark():currentUser.getNickName()));
            iFriendshipService.addFriend(initFriendShip(friendRequest.getFriendId(),friendRequest.getMyId(),requestSender.getNickName()));
        }
        return Boolean.TRUE;
    }
    private Friendship initFriendShip(String myId,String userId,String remark){
        Friendship friendship = new Friendship();
        friendship.setIsMsgIgnore((long) YesNoEnum.NO.getNumCode());
        friendship.setIsBlack((long) YesNoEnum.NO.getNumCode());
        friendship.setMyId(String.valueOf(myId));
        friendship.setFriendId(userId);
        friendship.setFriendRemark(remark);
        friendship.setCreatedTime(new Date());
        friendship.setUpdatedTime(new Date());
        return friendship;
    }
}
